<?php

class Model_Listing_Preview extends Model_Listing implements Model_Listing_Interface
{
    protected static  $_collection = 'listing_preview';


    protected static $_requirements = array(
     //   'em'  => array('Required', 'Validator:EmailAddress'), //Email
    );

    //protected $_category = array();

    public function __construct($data = array(), $config = array()) {
        static::$_transcript = array_merge(array(
        ), static::$_transcript);
        $config['collection'] = 'listing_preview';
        parent::__construct($data, $config);
        
        //$this->_category = $this->category;
    }

    public function postAnAddForm($options = array()) {
        $options = array_merge($options, array('category' => $this->category));
        return new Listing_Form_PostAnAddRegularForm($options);
    }

    public static function saveAsListing(Model_Listing $model)
    {
        $arr = array();

        //var_dump($model->export());
        foreach ($model as $k => $v) {
            //var_dump($k, $v);
            $arr[$k] = $v;
        }
        
        $connection = Shanty_Mongo::getWriteConnection(self::$_connectionGroup);
        $db  = $connection->selectDB(self::$_db);
        $mco = $db->selectCollection(Model_Listing::$_collection);
        $ad  = Model_Listing::find(new MongoId($arr['_id']));        
        
        //Create a new Ad
        //echo '<PRE>model';
        //var_dump($model);
        //var_dump($arr);
        if (empty($ad)) {
            $cat = $arr['ca'];
            $tmp = array();
            foreach ((array)$cat as $data) {
                $data1 = Model_Category::one(array('_id' => new MongoId($data)));
                $parent = $data1->getParentTree();
                foreach ((array)$parent as $k) {
                    if (in_array((string)$k->_id, $tmp)) {
                        continue;
                    }
                    $tmp[] = (string)$k->_id;
                    $k->listing_count = $k->listing_count + 1;
                    $k->save();
                }
            }
        }
        elseif ($ad->status != $arr['sa']) {
            //$cat = new MongoId($arr['ca']);
            $tmp = array();
            foreach ((array)$arr['ca'] as $data) {
                if (!is_object($data)) {
                    file_put_contents('/tmp/ac_preview_error', print_r($ad), FILE_APPEND);
                }
                $cat = Model_Category::find($data);
                $parent = $cat->getParentTree();
                foreach ((array)$parent as $k) {
                    if (in_array((string)$k->_id, $tmp)) {
                        continue;
                    }
                    $tmp[] = (string)$k->_id;
                    $k->listing_count = $k->listing_count + 1;
                    $k->save();
                }
            }
        }
        //var_dump($arr);
        
        //exit;

        $mco->save($arr);
        $ad = Model_Listing::find(new MongoId($arr['_id']));
        //$ad->save();
        //force indexing by solr
        
        $ad->forceSave();
        //var_dump($ad);exit;
        return $ad;
    }

    public static function convertFromListing(Model_Listing $model)
    {
        $arr = array();

        foreach ($model as $k => $v) {
            $arr[$k] = $v;
        }

        //echo '<pre>';print_r($model);exit;
        /*
        if (!empty($arr['photos_tmp'])) {
            $arr['ph'] = $arr['photos_tmp'];
        }
        if (!empty($arr['ph'])) {
            $arr['photos_tmp'] = $arr['ph'];
        }
        */
        //echo '<pre>';echo get_class($model);print_r($arr);exit;
        $connection = Shanty_Mongo::getWriteConnection(self::$_connectionGroup);
        $db  = $connection->selectDB(self::$_db);
        $mco = $db->selectCollection(self::$_collection);
        //echo '<pre>';print_r($arr);exit;
        $mco->save($arr);
        //echo '<pre>';print_r($arr['_type']);exit;
        $ad = self::create($arr, false);
       // echo '<pre>';print_r($ad);exit;
        return $ad;
    }

    public static function one(array $query = array())
    {
        $inheritance = static::getCollectionInheritance();
        if (count($inheritance) > 1) {
                $query['_type'] = $inheritance[0];
        }
        unset($query['_type']);

        $data = static::getMongoCollection(false)->findOne($query);

        if (is_null($data)) {
            return null;
        }

        $res = static::create($data, false);
        $res->no_solr = 1;
        
        $res->ca = self::fixCategories($res->category);
        //var_dump($found, $res->category, $tmp);exit;        
        return $res;
    }

    public static function getInstance($classname, $id)
    {
        if (is_array($classname))  {
            throw new Exception('I think you wnat to use getInstanceClassname. Sorry, Olivier');
        }

        
        //just a little tweak to put the right classname (bypass Shanty)
        $connection = Shanty_Mongo::getWriteConnection(self::$_connectionGroup);
        $db = $connection->selectDB(self::$_db);
        $mco = $db->selectCollection(self::$_collection);
        $tmp = $mco->findOne(array('_id' => new MongoId($id)));
        if (!empty($tmp)) {
            unset($tmp['_t']);
            $tmp['_type'] = array($classname, 'Model_Listing');
            $mco->save($tmp);

            return static::create($tmp, false);
        }
        return null;
    }


    public function getQuickSearchTabs()
    {
        return array();
    }

    public function getQuickSearchForms()
    {

    }

    public function getAdDetailPartialName()
    {
        return '';
    }

    public function getAdPreviewPartialName()
    {
        return '';
    }
    
    public static function fixCategories($res)
    {
        //if category is from customized category change 
        $new_cats = array();

        $customized_cat = array(
            'c554' => 'storage',
            'c553' => 'storage',
            'c414' => 'apartments',
            'c413' => 'apartments',
            'c438' => 'houses',
            'c432' => 'houses',
                
        );
        $found = array();
        $tmp = $res;

        foreach($res as $k => $cat) {
            if (!empty($customized_cat[$cat->id])) {
                unset($tmp[$k]);
                if (empty($found[$customized_cat[$cat->id]])) {
                    $found[$customized_cat[$cat->id]] = 1;
                    $new_cats[] = Model_Category::one(array('id' => $customized_cat[$cat->id]))->_id;
                }
            } else {
                $new_cats[] = $cat->_id;
            }
        }

        //$res->ca = $new_cats;
        return $new_cats;
    }
	
	public static function translateAnAd( $id = null)
	{
	
            if ($id == null){
                    $list  = Model_Listing::one(array('sa' => 1, 'at' => -1));
            } else {
                    $list  = Model_Listing::one(array('_id' => new MongoId($id), 'sa' => 1, 'at' => -1));
                    if (empty($list)) {
                        $list  = Model_Listing::one(array('sa' => 1, 'at' => -1));
                    } 
            }
            if ($list instanceof Model_Listing) {
                $list->at = Model_Listing::ORIGINAL_LANGUAGE_EN;

                foreach($list::getTranslationFormField() as $v => $r){
                        $list->{$v} = $list->{$v};
                        if($v == 'cn_en'){
                                $list->{str_replace('en','tc', $v)} = $list->{$v};
                        } else {
                                $list->{str_replace('en','tc', $v)} = Ac_Translation::execute($list->{$v}, 'zh-TW', 'en');
                        }
                }
                if($list->_type[0] != 'Model_Listing_Job' && $list->_type[0] != 'Model_Listing_Maid'){
                        $list->st_en = $list->st;
                        $list->st_tc = $list->st;
                }
                $list->save();
            }
	
	}
}